﻿using SketchUpAPI.NET.Enums;
using SketchUpAPI.NET.SketchUp.Exception;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace SketchUpAPI.NET.Objects.Tables
{
    /// <summary>
    /// 群组定义表
    /// </summary>
    /// <remarks>
    /// 注意：该类型并非 SketchUpAPI 接口中存在的类型，而是该 API 为方便管理组件定义而创建的类型。该类型的 Id 使用的是 <see cref="SketchUp.SketchUpModel"/> 的 Id
    /// </remarks>
    public class GroupTable : ObjectBase
    {
        #region API 函数
        /// <summary>
        /// 获取群组定义的个数
        /// </summary>
        /// <param name="model"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUModelGetNumGroupDefinitions(IntPtr model, out int count);

        /// <summary>
        /// 获取全部群组定义
        /// </summary>
        /// <param name="model"></param>
        /// <param name="len"></param>
        /// <param name="definitions"><see cref="ComponentDefinition"/>[]</param>
        /// <param name="realcount"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUModelGetGroupDefinitions(IntPtr model, int len, ref IntPtr[] definitions, out int realcount);

        /// <summary>
        /// 删除组件定义，所有的实例将被自动释放。
        /// </summary>
        /// <param name="model"></param>
        /// <param name="len"></param>
        /// <param name="componentDefs"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUModelRemoveComponentDefinitions(IntPtr model, long len, IntPtr[] componentDefs);
        #endregion

        /// <summary>
        /// 群组定义的个数
        /// </summary>
        public int Count
        {
            get
            {
                SketchUpExceptionHelper.ThrowSUResult(SUModelGetNumGroupDefinitions(Id, out int count));
                return count;
            }
        }

        /// <summary>
        /// 群组定义
        /// </summary>
        public List<ComponentDefinition> Definitions
        {
            get
            {
                IntPtr[] pts = new IntPtr[Count];
                SketchUpExceptionHelper.ThrowSUResult(SUModelGetGroupDefinitions(Id, Count, ref pts, out int realcount));
                return pts.Select(p => new ComponentDefinition(p)).ToList();
            }
        }

        internal GroupTable(IntPtr id)
        {
            Id = id;
        }

        /// <summary>
        /// 删除组件定义，所有改组件的实例都将被自动释放
        /// </summary>
        /// <param name="defs"></param>
        public void Remove(ComponentDefinition[] defs)
        {
            SketchUpExceptionHelper.ThrowSUResult(SUModelRemoveComponentDefinitions(Id, defs.Length, defs.Select(de => de.Id).ToArray()));
        }
    }
}